﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using EnvDTE;
using System.IO;
using System.Threading;

using VSLangProj80;
using VSLangProj;
using EnvDTE80;

namespace CodeBuilder.Automation
{
    using CodeBuilder.Properties;
    public partial class AssemblyForm : Form
    {
        public AssemblyForm()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 加载工程解决方案
        /// </summary>
        private void LoadProjects()
        {
            this.treeView_Projs.Nodes.Clear();
         

            List<ProjectItem> projs = GetProjectItems();
            projs.ForEach(t => {
                Project proj = t.ContainingProject;

                TreeNode node = new TreeNode();
                node.Text = proj.Name;
                node.Tag = t;

                this.treeView_Projs.Nodes.Add(node);
            });   
        }

      

        /// <summary>
        /// 获取项目向
        /// </summary>
        /// <returns></returns>
        private List<ProjectItem> GetProjectItems()
        {
            List<ProjectItem> items = new List<ProjectItem>();
            //获取解决方案列表
            Projects projs = Solution.Projects;

            if (projs.Count > 0)
            {
                for (int i =1; i <= projs.Count; i++)
                {
                    Project proj = projs.Item(i);
                    if (proj.ProjectItems != null && proj.ProjectItems.Count > 0)
                    {
                        items.AddRange(GetSolutionProject(proj.ProjectItems));                        
                    }
                }
            }
            return items;
        }

        private string versionFile = "assemblyinfo.cs";
        private string properties = "properties";

        private List<ProjectItem> GetSolutionProject(ProjectItems piList)
        {
            List<ProjectItem> items = new List<ProjectItem>();
            if (piList.Count > 0)
            {
                for (int i = 1; i <= piList.Count; i++)
                {
                    ProjectItem item = piList.Item(i);
                    if (item != null)
                    {
                        ProjectItem newItem = GetSolutionProject(item);
                        if (newItem != null)
                        {
                            items.Add(newItem);
                        }
                    }
                }
            }
            return items;
        }

        private ProjectItem GetSolutionProject(ProjectItem pi)
        {
            if (pi != null && pi.ProjectItems!=null && pi.ProjectItems.Count>0)
            {
                for (int i = 1; i <= pi.ProjectItems.Count; i++)
                {
                    ProjectItem item = pi.ProjectItems.Item(i);
                    if (item != null && item.Name.ToLower().Equals(versionFile))
                    {
                        return item;
                    }
                }
            }

            if (pi != null && pi.SubProject != null && pi.SubProject.ProjectItems.Count > 0)
            {
                for (int i = 1; i <= pi.SubProject.ProjectItems.Count; i++)
                {
                    ProjectItem item = pi.SubProject.ProjectItems.Item(i);
                    if (item.Name.ToLower().Contains(properties))
                    {
                        if (item.ProjectItems != null && item.ProjectItems.Count > 0)
                        {
                            ProjectItem projItem = item.ProjectItems.Item(1);
                            if (projItem != null && projItem.Name.ToLower().Equals(versionFile))
                            {
                                return projItem;
                            }
                        }
                    }
                }
            }
            return null;
        }

       


        public Solution2 Solution
        {
            get
            {
                return (Solution2)EnvConfig.ApplicationObject.Solution;
            }
        }


        /// <summary>
        /// 写入版本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnWrite_Click(object sender, EventArgs e)
        {
            try
            {
                string version = txtVersion.Text.Trim();
                List<ProjectItem> items = new List<ProjectItem>();
                if (treeView_Projs.Nodes.Count > 0 && treeView_Projs.Nodes.Count > 0)
                {
                    foreach (TreeNode node in treeView_Projs.Nodes)
                    {
                        if (node.Checked && node.Tag != null)
                        {
                            items.Add(((ProjectItem)node.Tag));
                        }
                    }
                }

                if (items.Count == 0)
                {
                    MessageBox.Show("请选择解决方案工程！");
                    return;
                }
                if (MessageBox.Show("确定要改写所选择解决方案的版本吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    items.ForEach(t =>
                    {
                        if (t.Properties != null && t.Properties.Item(18) != null && t.Properties.Item(18).Value != null)
                        {
                            WriteVersion(t.Properties.Item(18).Value.ToString(), version, t.ContainingProject.Name);
                        }
                    });
                    RefreshListView();

                    MessageBox.Show("写入成功！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LogUtil.Write(ex.Message);
            }
        }

        private void WriteVersion(string path, string version, string projectName)
        {
            string versionData = Settings.Default.version;

            versionData = versionData.Replace("$AssemblyTitle$", projectName)
                .Replace("$AssemblyDate$", DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss"))
                .Replace("$AssemblyProduct$", projectName)
                .Replace("&Guid&", Guid.NewGuid().ToString())
                .Replace("$AssemblyVersion$", version)
                .Replace("$AssemblyYear$",DateTime.Now.ToString("yyyy"));

           
            //判断文件是否只读，只读则更改为正常。
            var fileInfo = new FileInfo(path);
            if (fileInfo.IsReadOnly)
            {
                fileInfo.Attributes = FileAttributes.Normal;
            }

            using (StreamWriter sw = new StreamWriter(path, false, Encoding.Default))
            {
                sw.Write(versionData);
            }
        }

        /// <summary>
        /// 加载项目工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AssemblyForm_Load(object sender, EventArgs e)
        {
            try
            {
                LoadProjects();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LogUtil.Write(ex.Message);
            }
        }

        private VSLangProj.References GetProjectReferences(Project project)
        {
            VSProject vsproject = null;
            if (project != null)
            {

                if (project.Kind == PrjKind.prjKindCSharpProject)
                {

                    //工程类型为C#工程,将project的Object成员转换为VSProject对象

                    vsproject = project.Object as VSProject;

                }

                if (vsproject != null)
                {
                    //获取C#工程的引用集
                }
            }
            return vsproject.References;
        }

        /// <summary>
        /// 选择相应的节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView_Projs_AfterSelect(object sender, TreeViewEventArgs e)
        {
            RefreshListView();
        }

        private void RefreshListView()
        {
            lvAssembly.Items.Clear();
            if (treeView_Projs.SelectedNode != null && treeView_Projs.SelectedNode.Tag != null)
            {
                Project project = ((ProjectItem)treeView_Projs.SelectedNode.Tag).ContainingProject;

                References refs = GetProjectReferences(project);

                if (refs != null && refs.Count > 0)
                {
                    for (int i = 1; i < refs.Count; i++)
                    {
                        Reference refItem = refs.Item(i);
                        ListViewItem item = new ListViewItem();
                        item.SubItems.Add(refItem.Name);
                        item.SubItems.Add(refItem.Version);
                        item.SubItems.Add(refItem.Description);
                        item.SubItems.Add(refItem.Identity);
                        item.SubItems.Add(refItem.Path);
                        lvAssembly.Items.Add(item);
                    }
                }

            }
        }

        /// <summary>
        /// 全新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_selectAll_CheckedChanged(object sender, EventArgs e)
        {
            if (treeView_Projs.Nodes.Count > 0 && treeView_Projs.Nodes.Count > 0)
            {
                foreach (TreeNode node in treeView_Projs.Nodes)
                {
                    node.Checked = checkBox_selectAll.Checked;
                }
            }

        }
    }
}
